package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.util.ResponseUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wanghaotian
 * time:2022/12/17,0017 9:11
 * description:
 */

@RestController
@CrossOrigin("*")
@RequestMapping("/admin/admin")
public class AdminAdminController {

    @Autowired
    private DtsAdminService adminService;

    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "查询")
    @GetMapping("/list")
    public Object list(
            @RequestParam(value = "page" ,defaultValue = "1",required = false) Integer page,
            @RequestParam(value = "limit" ,defaultValue = "20",required = false) Integer limit,
            String username,String sort,String order
    ){
        IPage<DtsAdmin> iPage = adminService.findList(page,limit,username,sort,order);
        Map<String,Object> data = new HashMap<>();
        data.put("total", iPage.getTotal());
        data.put("items", iPage.getRecords());
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody DtsAdmin admin){
        DtsAdmin admin1 = adminService.findAdminByUsername(admin.getUsername());
        if(admin1 != null){
            return ResponseUtil.fail(-1, "用户已存在");
        }
        adminService.addAdmin(admin);
        return ResponseUtil.ok(admin);
    }

    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsAdmin admin){
        adminService.updateAdmin(admin);
        return ResponseUtil.ok(admin);
    }

    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsAdmin admin){
        try {
            adminService.deleteById(admin);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, e.getMessage());
        }
        return ResponseUtil.ok();
    }
}
